package developerworks.jetty6;
import java.io.IOException;
import javax.jms.*;
import javax.naming.InitialContext;
import java.io.Serializable;

public class EventSubscriber
{
	private TopicConnectionFactory connectionFactory;
    private Topic eventsTopic;
    private TopicConnection connection;
    private TopicSession session;
	private TopicPublisher eventsPublisher;
	private TopicPublisher messagesPublisher;
    public EventSubscriber(){
		try
        {
            InitialContext ic = new InitialContext();
            Object o = ic.lookup("java:comp/env/jms/connectionFactory");
            connectionFactory = (TopicConnectionFactory)o;
            eventsTopic = (Topic)ic.lookup("java:comp/env/jms/events");
            Topic messagesTopic = (Topic)ic.lookup("java:comp/env/jms/messages");
            
            connection = connectionFactory.createTopicConnection();
            session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
            
            
            TopicSubscriber eventsSubscriber = session.createSubscriber(eventsTopic);
            TopicSubscriber messagesSubscriber = session.createSubscriber(messagesTopic);
            
            MessageListener topicListener = new ApplicationAddressBook();
            eventsSubscriber.setMessageListener(topicListener);
            
            messagesSubscriber.setMessageListener(new MessageEventListener());
            
            eventsPublisher = session.createPublisher(eventsTopic);
            messagesPublisher = session.createPublisher(messagesTopic);
            
            
            connection.start();
            System.out.println("RUNNING EVENTS");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
	}
	

    public void publish(Serializable s)
    {
        try
        {
            ObjectMessage m = session.createObjectMessage(s);
            eventsPublisher.publish(m);
            //connection.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    public void sendMessage(String mess){
    	try{
    		TextMessage m = session.createTextMessage( mess);
    		messagesPublisher.publish(m);
    	}catch (Exception e)
        {
            e.printStackTrace();
        }
    	
    }

}